package com.sunhao.gulimall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunhao.common.utils.PageUtils;
import com.sunhao.common.utils.Query;

import com.sunhao.gulimall.product.dao.CategoryDao;
import com.sunhao.gulimall.product.entity.CategoryEntity;
import com.sunhao.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(new Query<CategoryEntity>().getPage(params), new QueryWrapper<CategoryEntity>());

        return new PageUtils(page);
    }

    /**
     * 查询所有分类及子分类 并以树形结构返回
     * 1.找到所有的一级分类 stream.filter，2.根据一级分类递归查找子分类
     *
     * @return 三级分类列表
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        //查出分类的所有数据
        List<CategoryEntity> data = this.baseMapper.selectList(null);
        List<CategoryEntity> level1Menus = data.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == 0;
        }).map((categoryEntity) -> {
            categoryEntity.setChildren(getChildren(categoryEntity, data));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return level1Menus;
    }

    @Override
    public void removeMenusByIds(List<Long> list) {
        this.baseMapper.deleteBatchIds(list);
    }

    /**
     * 递归查询所有子分类
     *
     * @param root 父分类
     * @param all  所有分类
     * @return 子分类
     */
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(category -> {
            //获取一级子分类，递归出口
            return category.getParentCid() == root.getCatId();
        }).map(category -> {
            //递归查询二级、三级子分类
            category.setChildren(getChildren(category, all));
            return category;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return children;
    }

}